package com.zhz.common.tool.mybatisplus.base.dal.utils;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring工具类
 * @author  zhouhengzhe
 */
public class SpringContext implements ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(SpringContext.class);
    private static ApplicationContext applicationContext;

    public SpringContext() {
        log.info("### base init : SpringContext ###");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getHandler(String name, Class<T> cls) {
        T t = null;
        if (StrUtil.isNotEmpty(name)) {
            checkApplicationContext();

            try {
                t = applicationContext.getBean(name, cls);
            } catch (Exception var4) {
                log.error("####################" + name + "未定义");
            }
        }

        return t;
    }

    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContext");
        }
    }
}